import 'dart:async';
import 'dart:io';

import 'package:flutter_axrjc/datasource/network/api/LightApi.dart';
import 'package:flutter_axrjc/datasource/network/bean/BackColorBean.dart';
import 'package:flutter_axrjc/datasource/network/bean/EventBean.dart';
import 'package:flutter_axrjc/datasource/network/bean/LightBean.dart';
import 'package:flutter_axrjc/datasource/network/request/exp.dart';
import 'package:flutter_axrjc/main.dart';
import 'package:flutter_axrjc/util/AccelerationUtil.dart';
import 'package:flutter_axrjc/util/DeviceInfoUtil.dart';
import 'package:flutter_axrjc/util/LightUtil.dart';
import 'package:flutter_axrjc/util/TimerUtil.dart';
import 'package:flutter_axrjc/util/Util.dart';
import 'package:flutter_axrjc/widget/dialog.dart';
import 'package:flutter_axrjc/widget/select_lamp_dialog/view.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:share_plus/share_plus.dart';

import 'state.dart';

class MainHomeLogic extends GetxController
    with GetSingleTickerProviderStateMixin {
  final MainHomeState state = MainHomeState();
  LightUtil lightUtil = LightUtil();
  AccelerationUtil accelerationUtil = AccelerationUtil();
  TimerUtil timerUtil = TimerUtil();
  StreamSubscription<EventBean>? eventListener;
  @override
  void onInit() {
    super.onInit();
    lightUtil.addFinishListener((max, min, ave) {
      timerUtil.interrupt();
      accelerationUtil.interrupt();
      state.checkStatus.value = CheckStatusType.end;
      state.detectionAverageValue.value = ave.toStringAsFixed(2);
      state.endTime.value = DateTime.now();
      state.min = min;
      state.max = ave;
      showUploadDialog();
    });
    eventListener = eventBus.on<EventBean>().listen((event) {
      if (event.type == EventType.newCheck) {
        var light = event.data as LightBean;
        state.currentLampBean.value = light;
      }
      if (event.type == EventType.mobildMoving) {
        state.checkStatus.value = CheckStatusType.pause;
        timerUtil.pause();
        lightUtil.pause();
        showTipDialogOnce(
            content: "测试中，请勿移动手机，避免测量结果误差",
            onConfirmText: "继续测量",
            onConfirm: () {
              timerUtil.resume();
              lightUtil.resume();
              state.checkStatus.value = CheckStatusType.checking;
            });
      }
    });
    DeviceInfoUtil.getInfo().then((value) {
      state.device.value = "${value.brand}-${value.model}";
    });
  }

  Future<void> selectLamp() async {
    var res = await Get.dialog(const SelectLampDialog());
    if (res is LightBean) {
      state.currentLampBean.value = res;
      state.checkStatus.value = CheckStatusType.before;
    }
  }

  Future<void> startCheck() async {
    state.startTime.value = DateTime.now();
    if (state.currentLampBean.value == null) {
      EasyLoading.showToast("请选择灯具");
    } else {
      bool res =
          await checkLastDevice("${state.currentLampBean.value?.fixtureId}");
      if (!res) {
        print("没有点击继续检测");
        interrupt();
        return;
      }
      if (true != await showCountDown(3)) {
        print("结束");
        return;
      }
      Duration time = Duration(
          milliseconds: int.tryParse(
                  '${state.currentLampBean.value?.sysCode?.codeValue}') ??
              180000);
      state.checkStatus.value = CheckStatusType.checking;
      accelerationUtil.startCheck();
      timerUtil.startCountdown(time, (d) {
        state.countdown.value = "${(d.inSeconds).abs()}";
      }, () {
        lightUtil.finish();
      });
      lightUtil.startCheck(
        onChecking: (BackColorBean backColor) {
          if (!Platform.isAndroid) {
            state.currentLux.value = backColor.lux.toStringAsFixed(2);
          } else {
            state.currentLux.value = backColor.androidLux.toStringAsFixed(2);
          }
        },
      );
    }
  }

  Future<void> checkFinish(
      {required DateTime startTime,
      required String detectionMaxValue,
      required String detectionMinValue,
      required String detectionAverageValue}) async {
    var light = state.currentLampBean.value;
    if (light != null) {
      try {
        var endTime = DateTime.now();
        await LightApi.uploadLux(
            checkOs: Platform.isAndroid ? "android" : 'ios',
            detectionAverageValue: detectionAverageValue,
            detectionEndTime:
                Util.date2String(endTime, pattern: "yyyy-MM-dd HH:mm:ss") ?? '',
            detectionMaxValue: detectionMaxValue,
            detectionMinValue: detectionMinValue,
            detectionStartTime:
                Util.date2String(startTime, pattern: "yyyy-MM-dd HH:mm:ss") ??
                    '',
            fixtureBrand: state.currentLampBean.value?.fixtureBrand ?? '',
            fixtureId: state.currentLampBean.value?.fixtureId ?? '',
            fixtureModel: state.currentLampBean.value?.fixtureModel ?? '',
            fixtureType: state.currentLampBean.value?.fixtureType ?? '');
        EasyLoading.showToast("上传成功");
      } on ApiException catch (e) {
        EasyLoading.showToast(e.message);
      } catch (e) {
        print("$e");
      }
    }
  }

  @override
  void onClose() {
    super.onClose();
    eventListener?.cancel();
    interrupt();
    lightUtil.dispose();
    accelerationUtil.onClose();
  }

  void interrupt() {
    accelerationUtil.interrupt();
    lightUtil.interrupt();
    timerUtil.interrupt();
    state.checkStatus.value = CheckStatusType.before;
    state.detectionAverageValue.value = "0";
    state.currentLux.value = "0";
  }

  void showUploadDialog() {
    showCommonDialog(
        onConfirmText: "提交检测记录",
        content:
            "时间:${Util.date2String(state.startTime.value, pattern: "HH时:mm分")}-${Util.date2String(state.endTime.value, pattern: "HH时:mm分")}\n"
            "最大亮度：${state.max.toStringAsFixed(2)}\n"
            "最小亮度：${state.min.toStringAsFixed(2)}\n"
            "平均亮度：${state.detectionAverageValue.value}\n",
        onConfirm: () {
          Get.back();
          checkFinish(
              startTime: state.startTime.value,
              detectionMaxValue: '${state.max}',
              detectionMinValue: '${state.min}',
              detectionAverageValue: state.detectionAverageValue.value);
        },
        onCancel: () {
          Get.back();
        });
  }

  void share() {
    if (state.checkStatus.value == CheckStatusType.end) {
      Share.share("灯具：${state.currentLampBean.value?.fixtureName}的检测结果：\n"
          "时间:${Util.date2String(state.startTime.value, pattern: "HH时:mm分")}-${Util.date2String(state.endTime.value, pattern: "HH时:mm分")}\n"
          "最大亮度：${state.max.toStringAsFixed(2)}\n"
          "最小亮度：${state.min.toStringAsFixed(2)}\n"
          "平均亮度：${state.detectionAverageValue.value}\n"
          // "平均色温：${state.averageTemp.toStringAsFixed(2)}"
          );
    } else {
      EasyLoading.showToast("请先检测");
    }
  }

  Future<void> switchCamera() async {
    if (state.checkStatus.value != CheckStatusType.checking) {
      EasyLoading.show(status: "切换中");
      await lightUtil.switchCamera();
      state.isFront.value =
          lightUtil.controller?.description.lensDirection.name == "front";
      EasyLoading.dismiss();
    } else {
      EasyLoading.showToast("检测结束后切换摄像头");
    }
  }

  Future<bool> checkLastDevice(String s) async {
    String lastMobile = await LightApi.getPreCheckMobile(fid: s);
    if (state.device.value != lastMobile) {
      Completer<bool> completer = Completer<bool>();
      await showCommonDialog(
          content: "系统监测到本次灯具监测手机型号与前一次不一致，对检测结果会有影响，请使用前次检测手机！",
          cancelText: "停止检测",
          onConfirmText: "继续检测",
          onConfirm: () {
            Get.back();
            completer.complete(true);
          },
          onCancel: () {
            Get.back();
            completer.complete(false);
          });
      return completer.future;
    } else {
      return true;
    }
  }
}
